/*
 * Copyright 1999-2016 yinhai.com.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jasig.cas.client.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import javax.naming.InitialContext;
import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

public class ServerUtils {
	private static final Log logger = LogFactory.getLog(ServerUtils.class);
	private static int PORT = 0;
	private static int HTTP_PORT = 0;
	private static int HTTPS_PORT = 0;
	 
     public static int getPort(){
    	 if(PORT != 0)return PORT;
    	 try {
    		 MBeanServer server =  ManagementFactory.getPlatformMBeanServer();
    		 if(ServerDetector.isTomcat()){
    			    Set<ObjectName> objs = server.queryNames(new ObjectName("*:type=Connector,*"),Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
    			    for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
    			        ObjectName obj = i.next();
    			        String scheme = server.getAttribute(obj, "scheme").toString();
    			        String port = obj.getKeyProperty("port");
    			        if("https".equals(scheme)){
    			        	HTTPS_PORT = Integer.parseInt(port);
    			        }else if("http".equals(scheme)){
    			        	HTTP_PORT =  Integer.parseInt(port);
    			        }
    			    }
        	 }else if(ServerDetector.isWebLogic()){
        		 ObjectName service = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
        		 InitialContext ctx = new InitialContext();
        		 server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
        		 if(server == null){
        			 server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
        		 }
        		 ObjectName rt =  (ObjectName)server.getAttribute(service,"ServerRuntime");
        		 HTTP_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt,"ListenPort")));
        		 String sslEnabled = String.valueOf(server.getAttribute(rt,"SSLListenPortEnabled"));
        		 if("true".equals(sslEnabled)){
        			 HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt,"SSLListenPort")));
        		 }
        	 }else if(ServerDetector.isJBoss()){
        		 ObjectName service;
        		 try {
        			service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=https");
                	HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
				 } catch (Exception e) {
				 }
        	     service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http");
				 HTTP_PORT =  Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
        	 }else{
        		 logger.debug("Unsupport auto detect "+ServerDetector.getServerId()+" server port！Please set the rest port manually!");
             } 
		} catch (Exception e) {
			logger.debug("Get application server  port fail! Please make sure that application server`s JMX is enabled!");
		}
        if(HTTPS_PORT != 0){
     	   PORT = HTTPS_PORT;
     	}else{
     	   PORT = HTTP_PORT;
     	}
    	 return PORT;
     }

}
